package com.zbkj.client.callback;


import com.alibaba.fastjson.JSON;
import com.zbkj.client.enums.WebSocketEventType;
import com.zbkj.client.vo.DpVideoCjVo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.client.agent.Agent;
import com.zbkj.common.model.client.agent.AgentGroup;
import com.zbkj.common.model.client.digital.DgVideo;
import com.zbkj.common.model.client.discovery.Discovery;
import com.zbkj.common.request.client.DiscoveryRemoteAddRequest;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.service.AgentGroupService;
import com.zbkj.service.service.AgentService;
import com.zbkj.service.service.DiscoveryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/dr")
public class DiscoveryRemoteController {

    @Autowired
    private DiscoveryService discoveryService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentGroupService agentGroupService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${workbench.agent}")
    private String agentBaseUrl;



    /**
     *  python端 调用接口插入本地数据库
     * @param discoveryRemoteAddRequest
     * @return
     */
    @PostMapping("/createDiscovery")
    public CommonResult<Map<String, Object>> createDiscovery(@RequestBody DiscoveryRemoteAddRequest discoveryRemoteAddRequest) {
        try {
            log.info("接收到发现页面插入数据: {}", discoveryRemoteAddRequest);
            String type = discoveryRemoteAddRequest.getType();
            List<DiscoveryRemoteAddRequest> agentsInfo = discoveryRemoteAddRequest.getAgentsInfo();
            List<String> groupAgents = discoveryRemoteAddRequest.getAgentIds();
            Integer isShowDiscovery = discoveryRemoteAddRequest.getIsShowDiscovery();//是否显示在发现页

            //如果没有传linkId,就需要先调用创建
            String linkId = discoveryRemoteAddRequest.getLinkId();
            if (linkId == null || linkId.isEmpty()) {
                if ("agent".equals(type)) {
                    Map<String, Object> hashParam = createAgentParam(discoveryRemoteAddRequest);
                    Map<String, Object> agent = createAgentApi(hashParam);
                    linkId = agent.get("id").toString();
                }else{
                    Map<String, Object> hashParam = createGroupParam(discoveryRemoteAddRequest);
                    Map<String, Object> agent = createGroupApi(hashParam);
                    linkId = agent.get("id").toString();

                    //如果agentIds有值，则请求添加成员的接口
                    if(groupAgents != null && groupAgents.size() > 0){
                        for (String groupAgent : groupAgents){
                            HashMap<String, Object> addMap = new HashMap<>();
                            addMap.put("agent_id", groupAgent);
                            addMap.put("member_type", "member");
                            addGroupMember(linkId, addMap);
                        }
                    }
                }
            }

            discoveryRemoteAddRequest.setLinkId(linkId);

            Boolean Discoveryresult = true;

            //生成随机的userCount和userCount
            Integer userCount = (int)(Math.random() * 101) + 100;
            Integer useCount = (int)(Math.random() * 101) + 100;

            //如果只更新agent或者group,不更新发现页，则需要判断notDiscovery的值
            if(isShowDiscovery != null && isShowDiscovery == 1){
                // 根据link_id查找并更新记录
                Discovery discovery = discoveryService.lambdaQuery()
                        .eq(Discovery::getLinkId, discoveryRemoteAddRequest.getLinkId())
                        .eq(Discovery::getType, type)
                        .eq(Discovery::getIsDel, 0)
                        .one();

                if (discovery == null) {
                    Discoveryresult = insertDiscovery(discoveryRemoteAddRequest,useCount,userCount);
                } else {
                    Discoveryresult = updateDiscovery(discovery, discoveryRemoteAddRequest);
                }
            }

            Boolean agentResult = false;

            //判断是agent 还是 group
            if ("agent".equals(type)) {
                Agent agent = agentService.lambdaQuery()
                        .eq(Agent::getAgentId, discoveryRemoteAddRequest.getLinkId())
                        .eq(Agent::getIsDel, 0)
                        .one();

                if (agent == null) {
                    agentResult = insertAgent(discoveryRemoteAddRequest,useCount,userCount);
                }else{
                    Map<String, Object> hashParam = createAgentParam(discoveryRemoteAddRequest);
                    updateAgentApi(linkId,hashParam);
                    agentResult = updateAgent(agent, discoveryRemoteAddRequest);
                }
            }else if ("group".equals(type)) {
                AgentGroup agentGroup = agentGroupService.lambdaQuery()
                        .eq(AgentGroup::getGroupId, discoveryRemoteAddRequest.getLinkId())
                        .eq(AgentGroup::getIsDel, 0)
                        .one();

                if (agentGroup == null) {
                    agentResult = insertGroup(discoveryRemoteAddRequest,useCount,userCount);
                }else{
                    Map<String, Object> hashParam = createGroupParam(discoveryRemoteAddRequest);
                    updateGroupApi(linkId,hashParam);
                    agentResult = updateGroup(agentGroup, discoveryRemoteAddRequest);
                }
            }

            //如果agentsInfo有传值，那么就插入数据库
            if (agentsInfo != null && !agentsInfo.isEmpty()){
                for (DiscoveryRemoteAddRequest agentInfo : agentsInfo) {
                    Agent agentLoop = agentService.lambdaQuery()
                            .eq(Agent::getAgentId, agentInfo.getLinkId())
                            .eq(Agent::getIsDel, 0)
                            .one();

                    if (agentLoop == null) {
                       insertAgent(agentInfo,useCount,userCount);
                    }else{
                        updateAgent(agentLoop, agentInfo);
                    }
                }
            }

            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("linkId", discoveryRemoteAddRequest.getLinkId());
            resultMap.put("type", discoveryRemoteAddRequest.getType());
            return CommonResult.success(resultMap);
        } catch (Exception e) {
            log.error("处理agent插入异常", e);
            return CommonResult.failed("服务器发生异常: "+e.getMessage());
        }
    }


    //插入agent表
    private Boolean insertAgent(DiscoveryRemoteAddRequest discoveryRemoteAddRequest,Integer useCount, Integer userCount){
        Agent agent = new Agent();
        agent.setAgentId(discoveryRemoteAddRequest.getLinkId());
        agent.setAuthor(discoveryRemoteAddRequest.getAuthor());
        agent.setTag(discoveryRemoteAddRequest.getTag());
        agent.setTitle(discoveryRemoteAddRequest.getTitle());
        agent.setDescription(discoveryRemoteAddRequest.getDescription());
        agent.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        agent.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        agent.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());
        agent.setUserCount(userCount);
        agent.setUseCount(useCount);

        return agentService.save(agent);
    }

    //更新agent表
    private Boolean updateAgent(Agent agent, DiscoveryRemoteAddRequest discoveryRemoteAddRequest){
        agent.setAgentId(discoveryRemoteAddRequest.getLinkId());
        agent.setAuthor(discoveryRemoteAddRequest.getAuthor());
        agent.setTag(discoveryRemoteAddRequest.getTag());
        agent.setTitle(discoveryRemoteAddRequest.getTitle());
        agent.setDescription(discoveryRemoteAddRequest.getDescription());
        agent.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        agent.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        agent.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());

        return agentService.updateById(agent);
    }

    //插入group表
    private Boolean insertGroup(DiscoveryRemoteAddRequest discoveryRemoteAddRequest,Integer useCount, Integer userCount){
        AgentGroup agentGroup = new AgentGroup();

        agentGroup.setGroupId(discoveryRemoteAddRequest.getLinkId());
        agentGroup.setAgentIds(discoveryRemoteAddRequest.getAgentIds());
        agentGroup.setAuthor(discoveryRemoteAddRequest.getAuthor());
        agentGroup.setTag(discoveryRemoteAddRequest.getTag());
        agentGroup.setTitle(discoveryRemoteAddRequest.getTitle());
        agentGroup.setDescription(discoveryRemoteAddRequest.getDescription());
        agentGroup.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        agentGroup.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        agentGroup.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());
        agentGroup.setUserCount(userCount);
        agentGroup.setUseCount(useCount);

        return agentGroupService.save(agentGroup);
    }

    //更新group表
    private Boolean updateGroup(AgentGroup agentGroup, DiscoveryRemoteAddRequest discoveryRemoteAddRequest){
        agentGroup.setGroupId(discoveryRemoteAddRequest.getLinkId());
        agentGroup.setAgentIds(discoveryRemoteAddRequest.getAgentIds());
        agentGroup.setAuthor(discoveryRemoteAddRequest.getAuthor());
        agentGroup.setTag(discoveryRemoteAddRequest.getTag());
        agentGroup.setTitle(discoveryRemoteAddRequest.getTitle());
        agentGroup.setDescription(discoveryRemoteAddRequest.getDescription());
        agentGroup.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        agentGroup.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        agentGroup.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());
//        agentGroup.setUserCount(15);
//        agentGroup.setUseCount(15);

        return agentGroupService.updateById(agentGroup);
    }

    //插入discovery表
    private Boolean insertDiscovery(DiscoveryRemoteAddRequest discoveryRemoteAddRequest, Integer useCount, Integer userCount){
        Discovery discoveryInsert = new Discovery();
        discoveryInsert.setLinkId(discoveryRemoteAddRequest.getLinkId());
        discoveryInsert.setType(discoveryRemoteAddRequest.getType());
        discoveryInsert.setAuthor(discoveryRemoteAddRequest.getAuthor());
        discoveryInsert.setTag(discoveryRemoteAddRequest.getTag());
        discoveryInsert.setTitle(discoveryRemoteAddRequest.getTitle());
        discoveryInsert.setDescription(discoveryRemoteAddRequest.getDescription());
        discoveryInsert.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        discoveryInsert.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        discoveryInsert.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());
        discoveryInsert.setSort(discoveryRemoteAddRequest.getSort());
        discoveryInsert.setUserCount(userCount);
        discoveryInsert.setUseCount(useCount);

        return discoveryService.save(discoveryInsert);
    }

    //插入discovery表
    private Boolean updateDiscovery(Discovery discovery, DiscoveryRemoteAddRequest discoveryRemoteAddRequest){
        discovery.setLinkId(discoveryRemoteAddRequest.getLinkId());
        discovery.setType(discoveryRemoteAddRequest.getType());
        discovery.setAuthor(discoveryRemoteAddRequest.getAuthor());
        discovery.setTag(discoveryRemoteAddRequest.getTag());
        discovery.setTitle(discoveryRemoteAddRequest.getTitle());
        discovery.setSort(discoveryRemoteAddRequest.getSort());
        discovery.setDescription(discoveryRemoteAddRequest.getDescription());
        discovery.setPackageLevel(discoveryRemoteAddRequest.getPackageLevel());
        discovery.setHeadImg(discoveryRemoteAddRequest.getHeadImg());
        discovery.setVideoUrl(discoveryRemoteAddRequest.getVideoUrl());
//                discovery.setUserCount(15);
//                discovery.setUseCount(15);

        return discoveryService.updateById(discovery);
    }

    //拼接请求agent接口的参数
    private Map<String, Object> createAgentParam(DiscoveryRemoteAddRequest discoveryRemoteAddRequest){
        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("name", discoveryRemoteAddRequest.getTitle());
        hashMap.put("description", discoveryRemoteAddRequest.getDescription());
        hashMap.put("model_id", discoveryRemoteAddRequest.getModelId());
        hashMap.put("planning_model_id", discoveryRemoteAddRequest.getPlanningModelId());
        hashMap.put("parameters", discoveryRemoteAddRequest.getParameters());
        hashMap.put("role_data", discoveryRemoteAddRequest.getRoleData());
        hashMap.put("user_info_map", discoveryRemoteAddRequest.getUserInfoMap());

        return hashMap;
    }

    //拼接请求群组的参数
    private Map<String, Object> createGroupParam(DiscoveryRemoteAddRequest discoveryRemoteAddRequest){
        HashMap<String, Object> hashMap = new HashMap<>();

        /**
         * {
         *   "description": "负责产品设计和开发的AI代理群组",
         *   "group_prompt": "你们是一个产品开发团队，需要协作完成产品设计和开发任务。请各自发挥专业优势，共同完成用户需求。",
         *   "group_type": "work",
         *   "model_id": "8a418db7-b698-423f-8530-9343dc3a2ae3",
         *   "name": "产品开发团队",
         *   "properties": {
         *     "max_members": 10
         *   }
         * }
         */
        hashMap.put("name", discoveryRemoteAddRequest.getTitle());
        hashMap.put("description", discoveryRemoteAddRequest.getDescription());
        hashMap.put("model_id", discoveryRemoteAddRequest.getModelId());

        hashMap.put("group_prompt", discoveryRemoteAddRequest.getGroupPrompt());
        hashMap.put("group_type", discoveryRemoteAddRequest.getGroupType());
        hashMap.put("properties", discoveryRemoteAddRequest.getProperties());

        return hashMap;
    }

    //调用接口创建agent
    private Map<String, Object> createAgentApi(Map<String, Object> paramMap){
        String requestUrl = agentBaseUrl + "/api/v1/agents/create";
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Map> response = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, Map.class);
        Map<String, Object> respBody = response.getBody();
        if (respBody != null && Integer.valueOf(201).equals(respBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>)respBody.get("data");

            return data;
        } else {
            throw new CrmebException(respBody != null ? respBody.get("message").toString() : "创建代理失败");
        }
    }

    //调用接口创建agent
    private Map<String, Object> createGroupApi(Map<String, Object> paramMap){
        String requestUrl = agentBaseUrl + "/api/v1/groups/";
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Map> response = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, Map.class);
        Map<String, Object> respBody = response.getBody();
        if (respBody != null && Integer.valueOf(201).equals(respBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>)respBody.get("data");

            return data;
        } else {
            throw new CrmebException(respBody != null ? respBody.get("message").toString() : "创建群组失败");
        }
    }

    //调用接口更新agent
    private Map<String, Object> updateAgentApi(String agentId, Map<String, Object> paramMap){
        String requestUrl = agentBaseUrl + "/api/v1/agents/" + agentId;
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Map> response = restTemplate.exchange(requestUrl, HttpMethod.PUT, entity, Map.class);
        Map<String, Object> respBody = response.getBody();
        if (respBody != null && Integer.valueOf(200).equals(respBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>)respBody.get("data");

            return data;
        } else {
            throw new CrmebException(respBody != null ? respBody.get("message").toString() : "更新代理失败");
        }
    }

    //调用接口创建agent
    private Map<String, Object> updateGroupApi(String groupId, Map<String, Object> paramMap){
        String requestUrl = agentBaseUrl + "/api/v1/groups/" + groupId;
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Map> response = restTemplate.exchange(requestUrl, HttpMethod.PUT, entity, Map.class);
        Map<String, Object> respBody = response.getBody();
        if (respBody != null && Integer.valueOf(200).equals(respBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>)respBody.get("data");

            return data;
        } else {
            throw new CrmebException(respBody != null ? respBody.get("message").toString() : "创建群组失败");
        }
    }

    //添加成员到群组
    private Map<String, Object> addGroupMember(String groupId, Map<String, Object> paramMap){

        String requestUrl = agentBaseUrl + "/api/v1/groups/"+groupId+"/members";
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Map> response = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, Map.class);
        Map<String, Object> respBody = response.getBody();
        if (respBody != null && Integer.valueOf(201).equals(respBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>)respBody.get("data");

            return data;
        } else {
            throw new CrmebException(respBody != null ? respBody.get("message").toString() : "创建群组失败");
        }
    }
}
